package com.zhuangjie.order.service.impl;

import com.zhuangjie.mvc.sse.entity.SSEResult;
import com.zhuangjie.mvc.sse.service.AbstractSSEService;
import com.zhuangjie.order.dto.RiderLocationUpdateDTO;
import com.zhuangjie.order.enums.UserSSEMessageType;
import com.zhuangjie.order.service.UserSSEService;
import com.zhuangjie.security.provider.UserProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class UserSSEServiceImpl extends AbstractSSEService<Long> implements UserSSEService {


    @Override
    public void orderStateChange(Long userId, Long orderId) {
        if (userId == null && (userId = UserProvider.currentUserId()) == null) {
            throw new RuntimeException("在准备通知用户订单改变时，无法确认用户id!");
        }
        try {
            SSEResult sseResult = new SSEResult();
            sseResult.setData(orderId);
            sseResult.setMessageType(UserSSEMessageType.ORDER_STATE_CHANGE);
            send(userId, sseResult);
        } catch (Exception e) {
            log.error("发送订单状态已经改变通知给用户！");
        }
    }

    @Override
    public void riderLocationUpdate(RiderLocationUpdateDTO riderLocationUpdateDTO) {
        riderLocationUpdateDTO.getUserIds().forEach(userId -> {
            SSEResult sseResult = new SSEResult();
            sseResult.setData(riderLocationUpdateDTO.getRiderLocation());
            sseResult.setMessageType(UserSSEMessageType.RIDER_LOCATION_UPDATE);
            try {
                send(userId, sseResult);
            } catch (IOException e) {
                throw new RuntimeException("发送骑手位置更新通知给用户失败！");
            }
        });

    }
}
